#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 长颈鹿上传充装信息到全国服务平台，以冲压用户角色登录系统，自动完成上传操作
#
#  1、base64_api 验证码识别API。
#  2、login_tsyd_cnse 登录到动式压力容器公共信息服务平台 True表示登录成功。
#  3、get_submit_fill_list 获取充装系统的待上传的冲压数据列表。
#  4、do_submit_fill_record 上传一条冲压数据。
#  5、do_report_submit_status 往充装系统报告
#
# http://tsyd.cnse.gov.cn/Home/Login
#
#

import json
import time
import requests
import base64
import io
from io import BytesIO
from PIL import Image
from sys import version_info
from lxml import etree

ROOT_URL = "http://tsyd.cnse.gov.cn" #根url
CLOUD_VALIDATE_USERMANE = "nicholas_lcj" #云打码用户
CLOUD_VALIDATE_PASSWORD = "CJL123" #云打码账号
CNSE_USER_NAME = "中石化北海液化天然气有限责任公司" # 系统用户名
CNSE_PASSWORD = "7c4a8d09ca3762af61e59520943dc26494f8941b" #密码

CJL_INTERFACE_ROOT_URL = "" #长劲鹿接口的顶层目录

# UA伪装：将对应的User-Agent封装到一个字典中
headers = {
   'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Mobile Safari/537.36'
}

url = ROOT_URL + '/Home/Login'
response = requests.get(url=url, headers=headers)
sessionCJL = requests.session();
page_text = response.text


# 验证码识别
def base64_api(uname, pwd,  img):
    img = img.convert('RGB')
    buffered = BytesIO()
    img.save(buffered, format="JPEG")
    if version_info.major >= 3:
        b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
    else:
        b64 = str(base64.b64encode(buffered.getvalue()))
    data = {"username": uname, "password": pwd, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]
    return ""


# 登录到移动式压力容器公共信息服务平台
def login_tsyd_cnse(UserName=CNSE_USER_NAME,UserPassword=CNSE_PASSWORD):
    # 1.进入登录界面，获取页面内容

    # 2.识别验证码
    vCode = get_validate_code(page_text=page_text)
    print vCode

    # 3.拼装登录请求数据
    if do_login(vCode=vCode):
        print "登录系统成功。"
        return True


def do_login(vCode,UserName=CNSE_USER_NAME, UserPassword=CNSE_PASSWORD):
    timestamp = long(int(round(time.time() * 1000)))
    url = ROOT_URL + "/Home/Login?rand=" + str(timestamp)

    post_data = {
        "UserName": UserName,
        "UserPassword": UserPassword,
        "vCode" : vCode,
        "signMsg" : ""
    }
    # 提交登录请求
    response = sessionCJL.post(url=url, data=post_data, headers=headers)
    print response.text

    # 判断登录成功状态
    if response.status_code == 200:
        result = response.json()
        if result['RetCode'] == -1000:
            print result['Message']
            return login_tsyd_cnse()
        elif result['RetCode'] == 0:
            return True
        return False
    else:
        return False

# 获取验证码
# 根据页面内容，通过xpath获取验证码的图面的内容，并且将图片保存到本地
# 调用base64_api进行图片识别，将验证码返回
def get_validate_code(page_text):
    # 生成etree实例
    tree = etree.HTML(text=page_text)
    # 根据xpath表达式，获取验证码的元素,取出里面的src属性
    evcode_src = tree.xpath('// *[ @ id = "imgVCode"]/@src')[0]

    # 获取图片数据
    img_url = ROOT_URL+evcode_src
    yzmdata = sessionCJL.get(img_url,headers=headers)
    with io.open("validate.gif","wb") as fp:
        fp.write(yzmdata.content)

    # tempIm = BytesIO(yzmdata.content)
    img = Image.open("validate.gif")

    result = base64_api(uname=CLOUD_VALIDATE_USERMANE, pwd=CLOUD_VALIDATE_PASSWORD, img=img)
    print result
    return result;

# 刷新界面,60秒调用一次
def update_user_token():
    update_url = ROOT_URL + "/Home/UserTokenUpdate"
    sessionCJL.get(update_url,headers=headers)

# 查询需要上传的数据
# 调用长颈鹿的充装待上传记录
def get_submit_fill_list():
    return [];

# 上传一条充装记录
def do_submit_fill_record(fill):
    return True

# 验证UK
def check_uk(cert):
    timestamp = long(int(round(time.time() * 1000)))
    postdata={
        'ukeyName':cert,
        'signature':"222"
    }
    check_uk_url = ROOT_URL + "/Fill/CAFillRandGet?rand=" + str(timestamp)
    response = sessionCJL.post(url=check_uk_url,headers=headers)
    print response.text

# main 函数
if __name__ == "__main__":
    # 如果登录系统成功，调用自身服务获取上传文件列表
    # 循环调用
    if login_tsyd_cnse():
        check_uk(cert="F72E5EFD-F488-46B1-B42A-E14FEDBB19FF/A03RQ020745")
        # loop = 0;
        # while True:
        #     time.sleep(1)
        #     loop += 1
        #     loop = loop % 60
        #     if loop == 59 :
        #         update_user_token()
        #     print loop
            # 查询需要上传的充装数据
            # fill_list = get_submit_fill_list()
            # for fill in fill_list:



        # url_fillreport = 'http://tsyd.cnse.gov.cn/Fill/ReportSave/'
        # response = sessionCJL.get(url=url_fillreport,headers=headers)
        # print response.text
